/**
 * Created by Administrator on 2015/6/23 0023.
 */
define("ws", function () {
    var wsServer = 'ws://121.41.115.217:9999'; //服务器地址
    var ws;

    var reStartTime=3000//断线重连时间
    var heartTime=50000//心跳间隔时间
    function reStart(){

            if ('WebSocket' in window) {
                ws = new WebSocket(wsServer);
            } else if ('MozWebSocket' in window) {
                ws = new MozWebSocket(wsServer);
            } else {
                alert('WebSocket is not supported by this browser.');
                return
            }


    }
    reStart()

    ws.alive = true
    //ws.send("hello");//向服务器发送消息
//    alert(ws.readyState);//查看websocket当前状态
    ws.onopen = function (evt) {
//已经建立连接
        tip.on("websocket连接成功：" + wsServer, 1, 3000);
        console.log("连接成功："+evt)
        ws.alive = true;

wsREG()


        chat.contant="连接良好"

        //保持心跳
        setInterval(function(){
            ws.send("\r\n")
        },heartTime)
    };
    ws.onclose = function (evt) {
//已经关闭连接
        tip.on("websocket连接已关闭：" + wsServer, 1, 3000);
        console.log("连接关闭："+evt)
        ws.alive = false

        chat.contant="掉线"

        setTimeout(function(){
            reStart()
        },reStartTime)
    };

    ws.res=''
    ws.onmessage = function (evt) {
//收到服务器消息，使用evt.data提取
        //检测分包
        ws.res=ws.res+evt.data
        if(ws.res.slice(-2)==='\r\n') {
            //分包为末尾
            var ins = ws.res.split(',');//转换为数组
            var targetFn = ins[1];//解析目标动作

//            var decoded=ins[2].replace(/\[\|\]/g,",")
            //var decoded=decodeURIComponent(ins[2])//数据解码

            var v=ins.splice(2,ins.length)//剔除前两位，剩余部分为参数部分

//            var data = JSON.parse(decoded)//转换为json

            ws.res=''//清空分包缓存

            console.log(ins+","+targetFn)
            //执行回调
            if (typeof ws.todo[targetFn] == "function") {
                ws.todo[targetFn](v);//传入数据
            } else {
                tip.on("服务器返回了一个不认识的家伙：" + targetFn)
            }
        }




    };
    ws.onerror = function (evt) {
//产生异常
        ws.alive = false;
        tip.on("websocket连接错误：" + wsServer, 1, 3000)
        setTimeout(function(){
            reStart()
        },reStartTime)
    };
    ws.todo = {};

    ws.call = function (v,i,obj) {

        if(typeof obj=="string"){
            //直接发送
            ws.send(v+","+i+","+obj+'\r\n')

        }
        else{
            var d=JSON.stringify(obj)

            ready2Send= d.replace(/,/g,"[|]")//字符替换
            //ready2Send=encodeURIComponent(d)//加码

            console.log(ready2Send+'<='+d)

            var p=v+","+i+","+ready2Send+"\r\n"//拼接指令极其版本

            ws.send(p)
        }



    };
    //注册指令
    ws.reg = function (name, fn) {
        if (typeof name == "string") {
            if (typeof fn == "function") {
                try{
                    ws.todo[name] = fn
                    console.log("监听"+name+"事件的方法已就绪")
                }catch (e){
                    console.log(e)
                }

            }
            else {
                tip.on("传入的方法必须为函数:" + fn)
            }
        }
        else {
            tip.on("传入的名称必须为字符串:" + name)
        }

    }


//    return ws
    window.ws = ws
});


